package cn.nexttec.noteplayer.repository

import cn.nexttec.noteplayer.common.ld
import okhttp3.*
import okio.Buffer
import org.greenrobot.eventbus.android.BuildConfig
import java.io.IOException

val requestBodyString: (Request) -> String = {
    try {
        val copy = it.newBuilder().build()
        val buffer = Buffer()
        copy.body()?.writeTo(buffer)
        buffer.readUtf8()
    } catch (e: IOException) {
        ""
    }
}

class HttpInterceptor(val tag: String = "Interceptor") : Interceptor {

    var token:String = ""
    var terminalId:String = ""

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val urlPath = request.url().encodedPath()

        // 排除登录接口
        if (urlPath != "auth/login") {
            val token = token
            val terminalId = terminalId

            val builder = request.newBuilder()
            if (!token.isNullOrEmpty()) {
                builder.addHeader("x-access-token", token)
            }
            if (!terminalId.isNullOrEmpty()) {
                builder.addHeader("x-tenant-id", terminalId)
            }
            request = builder.build()
        }

        try {
            val response = chain.proceed(request)
            if (BuildConfig.BUILD_TYPE.contains("debug")) {
                tag ld "*****************************************************************************************"
                tag ld "request.url:${request.url()}"
                tag ld "request.method:${request.method()}"
                request.headers().names().forEach {
                    tag ld "request.header: $it=${request.header(it)}"
                }
                tag ld "request.body: ${requestBodyString(request)}"
                val responseBody = response.body()
                val source = responseBody!!.source()
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer()
                tag ld "Response.time: ${response.receivedResponseAtMillis() - response.sentRequestAtMillis()}"
                tag ld "Response.success: ${response.isSuccessful}"
                tag ld "Response.status: ${response.code()}"
                tag ld "Response.body: ${buffer.clone().readUtf8()}"
                val responseString = buffer.clone().readUtf8()
                tag ld "Response.body: $responseString"
                tag ld "*****************************************************************************************"
                return response
            } else {
                return response
            }

        } catch (e: Exception) {
            tag ld "服务器无法连接 ${request.url()}"
            tag ld "异常:"+e.message

            return Response.Builder()
                .request(request)
                .protocol(Protocol.HTTP_1_1)
                .code(404)
                .body(ResponseBody.create(MediaType.parse("text/plain"), "服务器无法连接 ${e.stackTraceToString()}"))
                .message("服务器无法连接")
                .build()
        }
    }
}
